package org.lc.kcjxzj.controller;

import org.lc.kcjxzj.dto.ImportResultDTO;
import org.lc.kcjxzj.service.ImportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/import")
public class ImportController {

    @Autowired
    private ImportService importService;

    @GetMapping
    public String showImportForm() {
        return "import-form";
    }

    @PostMapping
    public String handleFileUpload(
            @RequestParam(value = "semester", required = false) String semester,
            @RequestParam(value = "file", required = false) MultipartFile zipFile,
            @RequestParam(value = "excelFile", required = false) MultipartFile excelFile,
            Model model) {

        if (excelFile != null && !excelFile.isEmpty()) {
            // 处理Excel汇总表上传
            ImportResultDTO result = importService.importFromExcelSheet(excelFile, semester);
            model.addAttribute("result", result);
            return "import-result";
        } else if (zipFile != null && !zipFile.isEmpty()) {
            // 保持原有ZIP上传处理逻辑
            ImportResultDTO result = importService.importFromArchive(zipFile);
            model.addAttribute("result", result);
            return "import-result";
        } else {
            model.addAttribute("error", "请选择要上传的文件");
            return "import-form";
        }
    }
}
